package pro.ccy;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class CoreFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        // 将req强制类型转换为 HttpServletRequest 对象
        HttpServletRequest request = (HttpServletRequest) req;
        // 将resp强制类型转换为HttpServletResponse对象
        HttpServletResponse response = (HttpServletResponse) resp;
        String uri = request.getRequestURI();
        if ("/ccy/login.jsp".equals(uri) || uri.endsWith(".css")){
            // 此时拦截时登录页，允许通过
            chain.doFilter(req,resp);
            return;
        }

        //获取 session
        HttpSession session = request.getSession();
        Object uid = session.getAttribute("UID");
        if (uid ==null) {
            // 说明没有登录
            System.out.printf("拦截器：未登录");
            response.sendRedirect("/ccy/login.jsp");
            return;
        }

        //说明用户已经登录过，允许通过
        chain.doFilter(req,resp);

    }

    @Override
    public void destroy() {
        // 析构函数：当过滤器被销毁的时候被执行
    }
}
